package com.api.base.service.impl;

import com.api.base.dao.AdminUserMapper;
import com.api.base.model.AdminUser;
import com.api.base.model.AdminUserAdd;
import com.api.base.model.SysUserRole;
import com.api.base.model.User;
import com.api.base.service.AdminUserService;
import com.api.base.service.SysUserRoleService;
import com.api.base.service.UserService;
import com.api.core.service.AbstractService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import com.api.common.JSONUtils;
import com.api.core.response.Result;
import com.api.core.response.ResultGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * Created by wanghuiwen on 2021/04/01.
 */
@Service
@Transactional
public class AdminUserServiceImpl extends AbstractService<AdminUser> implements AdminUserService {
    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private UserService userService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Override
    public Result list(Map<String,Object> params, String order, Integer page, Integer size){
//        Map<String, Object> params = JSONUtils.json2map(search);
        Map<String, Object> orderParams = JSONUtils.json2map(order);
        for (String key : orderParams.keySet()) {
                if (orderParams.get(key) != null && orderParams.get(key).equals("ascending")) orderParams.put(key, "asc");
                if (orderParams.get(key) != null && orderParams.get(key).equals("descending")) orderParams.put(key, "desc");
            }
        PageHelper.startPage(page, size);
        List<Map<String, Object>> res = adminUserMapper.list(params, orderParams);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public void add(AdminUserAdd adminUserAdd) {
        if(adminUserAdd.getId()== null){
            User user = new User();
            user.setRegisterTime(new Date().getTime());
            String password = new BCryptPasswordEncoder().encode(adminUserAdd.getPassword());
            user.setPassword(password);
            user.setAvatar(adminUserAdd.getAvatar());
            user.setDisable(adminUserAdd.getDisable());
            user.setLoginName(adminUserAdd.getLoginName());
            userService.save(user);

            AdminUser adminUser = new AdminUser();
            adminUser.setDel(false);
            adminUser.setEmail(adminUserAdd.getEmail());
            adminUser.setPhone(adminUserAdd.getPhone());
            adminUser.setUserId(user.getId());
            this.save(adminUser);

            if(StringUtils.isNotEmpty(adminUserAdd.getRoles())){
                String [] roleIds = adminUserAdd.getRoles().split(",");
                for(int i=0;i<roleIds.length;i++){
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(user.getId());
                    sysUserRole.setRoleId(Integer.parseInt(roleIds[i]));
                    sysUserRoleService.save(sysUserRole);
                }
            }
        }else{
            User user = userService.findById(adminUserAdd.getId());
            user.setLoginName(adminUserAdd.getLoginName());
            user.setAvatar(adminUserAdd.getAvatar());
            String password = new BCryptPasswordEncoder().encode(adminUserAdd.getPassword());
            user.setPassword(password);
            user.setDisable(adminUserAdd.getDisable());
            userService.update(user);

            AdminUser adminUser = this.findById(adminUserAdd.getId());
            adminUser.setEmail(adminUserAdd.getEmail());
            adminUser.setPhone(adminUserAdd.getPhone());
            this.update(adminUser);

            if(StringUtils.isNotEmpty(adminUserAdd.getRoles())){


                List<SysUserRole> sysUserRoles = sysUserRoleService.getListByUserId(adminUserAdd.getId());
                sysUserRoleService.deleteByUserId(adminUserAdd.getId());
                String [] roleIds = adminUserAdd.getRoles().split(",");
                for(int i=0;i<roleIds.length;i++){
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(user.getId());
                    sysUserRole.setRoleId(Integer.parseInt(roleIds[i]));
                    sysUserRoleService.save(sysUserRole);
                }
            }
        }
    }

    @Override
    public void delete(Long id) {
        User user = userService.findById(id);
        user.setDisable(true);
        userService.update(user);

        AdminUser adminUser = this.findById(id);
        adminUser.setDel(true);
        this.update(adminUser);
    }
}
